<template>
  <div>
    <div>
      <el-dialog :title="title" :visible.sync="visible" :close-on-click-modal="false" @open="handleOpen" @close="handleClose">
        <el-form ref="campus" :model="campus" label-position="top" :rules="rules">
          <!-- <el-form-item label="校区编号">
            <el-input v-model="campus.campusId" autocomplete="off" readonly="" />
          </el-form-item> -->
          <el-form-item prop="campusName" label="分支机构名称">
            <el-input v-model="campus.campusName" autocomplete="off" maxlength="50" show-word-limit />
          </el-form-item>

          <el-form-item prop="orgId" label="所属机构">
            <!-- <el-input v-model="campus.orgId" autocomplete="off" /> -->
            <el-select v-model="campus.orgId" placeholder="请选择">
              <el-option
                v-for="o in org"
                :key="o.orgId"
                :value="o.orgId"
                :label="o.orgName"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="分支机构图片">

            <el-upload
              class="avatar-uploader"
              name="files"
              :action="url"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB,建议上传340*150的图片</div>
            </el-upload>
            <!-- <img v-if="type==2" :src="campus.campusImg" width="200px" height="120px"> -->
          </el-form-item>
          <el-form-item prop="orgType" label="分支机构分类">
            <!-- <el-input v-model="campus.orgType" autocomplete="off" /> -->
            <el-select v-model="campus.orgType" placeholder="请选择">
              <el-option
                v-for="t in orgT"
                :key="t.id"
                :value="t.id"
                :label="t.typeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分支机构介绍">
            <el-input v-model="campus.campusInfo" autocomplete="off" type="textarea" autosize maxlength="100" />
          </el-form-item>
          <el-form-item prop="contactTel" label="联系电话(座机)">
            <el-input v-model="campus.contactTel" autocomplete="off" type="number" />
          </el-form-item>
          <el-form-item label="分支机构邮箱">
            <el-input v-model="campus.campusEmail" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="bank" label="银行">
            <el-autocomplete
              v-model="campus.bank"
              class="inline-input"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              :trigger-on-focus="false"
              @select="handleSelect"
            />
          </el-form-item>
          <el-form-item prop="account" label="银行账号">
            <el-input v-model="campus.account" autocomplete="off" />
          </el-form-item>
          <el-form-item label="营业时间">
            <el-input v-model="campus.campusHours" autocomplete="off" placeholder="例：8:00~20:00" />
          </el-form-item>
          <el-form-item label="国家">
            <el-input v-model="campus.area" autocomplete="off" />
          </el-form-item>
          <!-- <el-form-item label="省">
            <el-input v-model="campus.provice" autocomplete="off" />
          </el-form-item>
          <el-form-item label="市">
            <el-input v-model="campus.city" autocomplete="off" />
          </el-form-item>
          <el-form-item label="区">
            <el-input v-model="campus.district" autocomplete="off" />
          </el-form-item> -->
          <el-form-item label="地区">
            <!-- <el-input v-model="org.orgAddress" autocomplete="off" /> -->
            <el-cascader
              v-model="selectedOptions"
              size="large"
              :options="options"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item prop="conntact" label="联系人">
            <el-input v-model="campus.conntact" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="contactNumber" label="联系人电话">
            <el-input v-model="campus.contactNumber" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="head" label="负责人">
            <!-- <el-input v-model="campus.head" autocomplete="off" /> -->
            <el-select v-model="campus.head" placeholder="请选择">
              <el-option
                v-for="chead in head"
                :key="chead.userId"
                :value="chead.userId"
                :label="chead.username"
              />
            </el-select>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="type==2" type="primary" @click="handleUpdate('campus')">修 改</el-button>
          <el-button v-if="type==1" type="primary" @click="handleAdd('campus')">添 加</el-button>
          <el-button @click="visible=false">返 回</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCampusById, addCampus, updateCampus } from '@/api/campus'
import { getAllOrg } from '@/api/org'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { getConsoleUserById, getUserByGroup } from '@/api/consoleUser'
import { getAllOrgType } from '@/api/orgType'
export default {
  components: {
  },
  props: {
    id: {
      default: 0,
      type: Number
    },
    visible: {
      default: false,
      type: Boolean
    },
    // 添加 1  更新 2
    type: {
      default: 0,
      type: Number
    },
    title: {
      default: '',
      type: String
    }
  },
  data() {
    var checkphone = (rule, value, callback) => {
    // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    var checkcard = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入银行卡号'))
      } else if (!this.isCard(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的银行卡号!'))
      } else {
        callback()
      }
    }
    return {
      url: process.env.VUE_APP_BASE_API + 'file/',
      campus: {},
      org: {},
      orgT: {},
      text: '',
      bindDialogVisible: false,
      imageUrl: '',
      options: regionData,
      selectedOptions: [],
      areaList: {},
      area: '',
      banks: [],
      head: {},
      rules: {
        campusName: [{ required: true, message: '分支机构名称不能为空', trigger: 'blur' }, { validator: this.validateCharacter, trigger: ['blur', 'change'] }],
        orgId: [{ required: true, message: '所属机构不能为空', trigger: 'blur' }],
        orgType: [{ required: true, message: '分支机构分类不能为空', trigger: 'blur' }],
        contactTel: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
        bank: [{ required: true, message: '银行不能为空', trigger: 'blur' }],
        account: [{ required: true, validator: checkcard, trigger: 'blur' }],
        conntact: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        contactNumber: [{ required: true, validator: checkphone, trigger: 'blur' }],
        head: [{ required: true, message: '负责人不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getAllOrg()
    this.getAllOrgType()
  },
  mounted() {
    this.banks = this.loadAll()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.campus.campusImg = this.imageUrl
      console.log(res)
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
      // return true
    },
    fetchData() {

    },

    handleOpen() {
      this.getAllHead()
      if (this.type === 2) {
        console.log('fatch data')
        getCampusById(this.id).then((resp) => {
          this.campus = resp.obj
          this.campus.orgType = String(this.campus.orgType)
          this.imageUrl = resp.obj.campusImg
          this.jiema()
          getConsoleUserById(this.campus.head).then((resp) => {
            this.head.push(resp.obj)
            console.log(this.head)
          })
        })
      }
    },

    handleAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addCampus(this.campus).then((resp) => {
            this.$notify({
              title: '添加成功',
              type: 'success'
            })
            this.$parent.fetchData()
          })
          this.visible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateCampus(this.id, this.campus).then((resp) => {
            this.$notify({
              title: '更新成功',
              type: 'success'
            })
            this.$parent.fetchData()
          })
          this.visible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleClose() {
      console.log('eeeeee')
      this.$emit('close', {})
      this.campus = {}
      this.imageUrl = ''
      this.selectedOptions = []
    },

    getAllOrg() {
      getAllOrg().then((resp) => {
        this.org = resp.obj
      })
    },

    getAllOrgType() {
      getAllOrgType().then((resp) => {
        this.orgT = resp.obj
      })
    },

    handleChange(value) {
      console.log(this.selectedOptions)
      this.campus.provice = CodeToText[value[0]]
      this.campus.city = CodeToText[value[1]]
      this.campus.district = CodeToText[value[2]]
    },
    jiema() {
      this.selectedOptions = [TextToCode[this.campus.provice].code, TextToCode[this.campus.provice][this.campus.city].code, TextToCode[this.campus.provice][this.campus.city][this.campus.district].code]
    },
    querySearch(queryString, cb) {
      var banks = this.banks
      var results = queryString ? banks.filter(this.createFilter(queryString)) : banks
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (banks) => {
        return (banks.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll() {
      return [
        { 'value': '国家开发银行' },
        { 'value': '中国进出口银行' },
        { 'value': '中国农业发展银行' },
        { 'value': '中国银行' },
        { 'value': '中国工商银行' },
        { 'value': '中国建设银行' },
        { 'value': '中国农业银行' },
        { 'value': '光大银行' },
        { 'value': '中国民生银行' },
        { 'value': '中信银行' },
        { 'value': '交通银行' },
        { 'value': '华夏银行' },
        { 'value': '招商银行' },
        { 'value': '兴业银行' },
        { 'value': '广发银行' },
        { 'value': '平安银行' },
        { 'value': '上海浦东发展银行' },
        { 'value': '恒丰银行' },
        { 'value': '浙商银行' },
        { 'value': '渤海银行' },
        { 'value': '中国邮政储蓄银行' },
        { 'value': '城市商业银行' },
        { 'value': '北京银行' },
        { 'value': '天津银行' },
        { 'value': '河北银行' },
        { 'value': '沧州银行' },
        { 'value': '唐山市商业银行' },
        { 'value': '承德银行' },
        { 'value': '张家口市商业银行' },
        { 'value': '秦皇岛银行' },
        { 'value': '邢台银行' },
        { 'value': '廊坊银行' },
        { 'value': '保定银行' },
        { 'value': '邯郸银行' },
        { 'value': '衡水银行' },
        { 'value': '晋商银行' },
        { 'value': '大同市商业银行' },
        { 'value': '长治银行' }

      ]
    },
    handleSelect(item) {
      console.log(item)
      this.campus.bank = item.value
    },
    getAllHead() {
      getUserByGroup(4).then((resp) => {
        this.head = resp.obj
      })
    },
    isCard(val) {
      if (!/^([1-9]{1})(\d{15}|\d{18})$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    isCellPhone(val) {
      if (!/^1[3456789]\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    // 特殊字符过滤
    checkSpecificKey(str) {
      var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          return false
        }
      }
      return true
    },

    // 验证字符串
    validateFontSize(rule, value, callback) {
      if (value.length < 30) {
        callback()
      } else {
        callback(new Error('字符串长度在1-30之间'))
      }
    },

    // 验证字符串
    validateCharacter(rule, value, callback) {
      if (this.checkSpecificKey(value)) {
        callback()
      } else {
        callback(new Error('请不要输入特殊字符'))
      }
    }
  }
}
</script>

<style scoped>
 .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 340px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
    .avatar {
      width: 340px;
      height: 150px;
      display: block;
    }
</style>
